package test;

import java.awt.Rectangle;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xhtmlrenderer.extend.FSCanvas;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.simple.PDFRenderer;

import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.internal.PdfVersionImp;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.Version;
import pres.hdy.htmltopdf.config.TemplateConfig;

public class UseOk {

	public static void main(String[] args) throws Exception {
		convertHtmlToPdf("home.ftl", "c:/w.pdf");
	}

	public static boolean convertHtmlToPdf(String inputFile, String outputFile) throws Exception {
		
		
		FileTemplateLoader file = new FileTemplateLoader(new File("d:/aaa/"));
		Configuration c = new Configuration(Configuration.VERSION_2_3_23);
		c.setTemplateLoader(file);
		c.setDefaultEncoding("utf-8");

		Template template = c.getTemplate(inputFile);
		StringWriter sb = new StringWriter();
		BufferedWriter bw=new BufferedWriter(sb);
		Map<String, String> a = new HashMap<>();
		a.put("name", "何德裕");
		a.put("url", "www.baidu.com");
		template.process(a, bw);
		String b = sb.toString();
		bw.flush();
		bw.close();
		System.out.println(b);
		OutputStream os = new FileOutputStream(outputFile);

		ITextRenderer renderer = new ITextRenderer();

		// String url = new File(inputFile).toURI().toURL().toString();
		
//		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
//				.parse(new ByteArrayInputStream(b.getBytes("utf-8")));
		
		renderer.setDocument("http://localhost:8080/Rcom/home.html");
		// 解决中文支持问题
		ITextFontResolver fontResolver = renderer.getFontResolver();
		// 前端页面需要设置页面字体,字体需要和后台一致
		fontResolver.addFont("C:/WINDOWS/Fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

		// 解决图片的相对路径问题

		// renderer.getSharedContext().setBaseURL("http://localhost:8080/vframe");

		renderer.layout();
		renderer.createPDF(os);
		os.flush();
		os.close();

		return true;
	}
}